#pragma once
#include <iostream>
#include <unistd.h>
#include <queue>
#include <pthread.h>
#include <time.h>
#include "mtx.hpp"
#define NUMSIZE 10
using namespace std;
template <class T>
class proCust
{
public:
    proCust(size_t size = NUMSIZE)
        : _size(size)
    {
        pthread_mutex_init(&_mtx, nullptr);
        pthread_cond_init(&_full, nullptr);
        pthread_cond_init(&_empty, nullptr);
    }
    void push(const T &x, int number)
    {
        Rmtx s(_mtx);
        cout<<"我抢到锁了"<<number<<" " <<&_mtx<<endl;
        sleep(1);
        while (_size == _q.size())
        {
            pthread_cond_signal(&_empty);
            pthread_cond_wait(&_full, &_mtx);
        }
        _q.push(x);
        cout << "我是生产者：" << number << "号"
             << "  "
             << "我的tid: " << pthread_self() << endl;
        
    }
    T pop(int number)
    {
        Rmtx s(_mtx);
        cout<<"我抢到锁了"<<number<<" " <<&_mtx<<endl;
        sleep(1);
        while (_q.size() == 0)
        {
            pthread_cond_signal(&_full);
            pthread_cond_wait(&_empty, &_mtx);
        }
        T x = _q.front();
        _q.pop();
        cout << "我是消费者：" << number << "号"
             << "  "
             << "我的tid: " << pthread_self() << endl;
        return x;
    }
    ~proCust()
    {
        pthread_mutex_destroy(&_mtx);
        pthread_cond_destroy(&_full);
        pthread_cond_destroy(&_empty);
    }

private:
    size_t _size;
    queue<T> _q;
    pthread_cond_t _full;
    pthread_cond_t _empty;
    pthread_mutex_t _mtx;
};